var defaultid = '3'
new Vue({
    el: "#app",
    data:{
        labelData: [],
        pointArray: [],
        cityData: [],
        propertyData: [],
        defaultCity: window.localStorage.getItem('city_id'),
        areaId: 0,
        handleStatus:false,
        lng: Number(window.localStorage.getItem('longitude'))?window.localStorage.getItem('longitude'):110.325525,
        lat: Number(window.localStorage.getItem('latitude'))?window.localStorage.getItem('latitude'):20.044049,
        minZoom: 11,
        maxZoom : 24,
        scrollData: [],
        cur: 0,
        search: {
            type: 'new',
            city: {},
            pmcType: [],
            direct:[],
            renovate: [],
            tags:[],
            apartname: '',
            ser_area: 0,
            sort: 'default',
            newhouse:{
                ser_average: 0,
                ser_pmc: 0,
                ser_status: 0,
                priceStatus: false,
                timeStatus: false
            },
            handroom:{
                ser_price: 0,
                ser_acreage: 0,
                ser_room:0,
                direction: 0,
                floor: 0,
                renovation: 0,
                tags: [],
                age: 0
            },
            rentalhouse:{
                ser_price: 0,
                ser_acreage: 0,
                ser_room:0,
                direction: 0,
                floor: 0,
                renovation: 0,
                type: ''
            }
        },
        rightStatus: true,
        rightAttr: 'right-list',
        page:1,
        loading: false,
        canloading: true,
        nomore: '',
        boxHeight: 0,
    },
    methods:{
        toggleCon(){
            if(this.rightStatus){
                this.rightAttr = 'right-list move'
                this.rightStatus = false
            }else{
                this.rightAttr = 'right-list'
                this.rightStatus = true
            }
        },
        initCityProperty() {
            var that = this
            var formData = {city_id: that.defaultCity,type:that.search.type}
            axios.post("/maproom/data",formData).then(function (res) {
                if(!res.data.error){
                    that.cityData = res.data.area
                    that.addMarker();//添加聚合点
                }else{
                    that.$Message.error('初始化失败，请稍后重试')
                }
            }).catch(function (error) {
                that.$Message.error('加载失败，请稍后重试')
            });
        },
        initMap(scrollZoom=this.minZoom) {
            var map = new BMap.Map("allMap", {enableMapClick: false, minZoom: this.minZoom, maxZoom: this.maxZoom});
            var point = new BMap.Point(this.lng, this.lat);//默认中心点
            map.centerAndZoom(point, scrollZoom);
            map.enableScrollWheelZoom(true);
            //监听地图级别缩放事件，当级别为11时默认加载集合点，扩大级别时显示详细点位数据
            var that = this
            map.addEventListener("zoomend", function () {
                var zoomLevel=map.getZoom(); //获取地图缩放级别
                if(zoomLevel==that.minZoom){
                    that.addMarker();
                }else{
                    //当存储的数据有数时直接加载视野数据，否则请求接口数据
                    if(that.labelData.length>0){
                        that.addViewLabel(that.labelData);
                    }else{
                        // 未点击行政区，则加载当前市区对应的所有楼盘
                        if(!that.areaId){
                            that.getAllProperty()
                        }
                        that.getAllLabel();
                    }
                }
            });
            return map;
        },
        getAllProperty() {
            this.loading = true
            var formData = {
                city_id: this.defaultCity,
                area_id: this.areaId,
                sort:this.search.sort,
                type: this.search.type,
                apartname: this.search.apartname,
                average: this.search.newhouse.ser_average,
                wytype: this.search.newhouse.ser_pmc,
                sale_status: this.search.newhouse.ser_status,
                hand_price: this.search.handroom.ser_price,
                hand_acreage: this.search.handroom.ser_acreage,
                hand_room: this.search.handroom.ser_room,
                hand_direction: this.search.handroom.direction,
                hand_floor: this.search.handroom.floor,
                hand_renovation: this.search.handroom.renovation,
                hand_tags: this.search.handroom.tags.sort(),
                hand_age: this.search.handroom.age,
                rental_price: this.search.rentalhouse.ser_price,
                rental_acreage: this.search.rentalhouse.ser_acreage,
                rental_room: this.search.rentalhouse.ser_room,
                rental_direction: this.search.rentalhouse.direction,
                rental_floor: this.search.rentalhouse.floor,
                rental_renovation: this.search.rentalhouse.renovation,
                rental_type: this.search.rentalhouse.type
            }
            var that = this
            axios.post("/maproom/alldata",formData).then(function (res) {
                that.loading = false
                if(!res.data.error){
                    that.propertyData = res.data.data
                    that.lng = res.data.data[0].longitude
                    that.lat = res.data.data[0].latitude
                    that.$nextTick(function () {
                        // if(that.search.apartname.length){
                        //     window.map = that.initMap(12);
                        // }
                        that.getAllLabel();//添加聚合点
                    })
                }else{
                    that.propertyData = []
                    that.$Message.info('没有查询到对应房源信息')
                    // window.map = that.initMap(12);
                }
            }).catch(function (error) {
                that.loading = false
                that.$Message.error('加载失败，请稍后重试')
            });
        },
        initAllProperty(){
            this.loading = true
            var formData = {
                city_id: this.defaultCity,
                sort:this.search.sort,
                area_id: this.areaId,
                type: this.search.type,
                apartname: this.search.apartname,
                average: this.search.newhouse.ser_average,
                wytype: this.search.newhouse.ser_pmc,
                sale_status: this.search.newhouse.ser_status,
                hand_price: this.search.handroom.ser_price,
                hand_acreage: this.search.handroom.ser_acreage,
                hand_room: this.search.handroom.ser_room,
                hand_direction: this.search.handroom.direction,
                hand_floor: this.search.handroom.floor,
                hand_renovation: this.search.handroom.renovation,
                hand_tags: this.search.handroom.tags.sort(),
                hand_age: this.search.handroom.age,
                rental_price: this.search.rentalhouse.ser_price,
                rental_acreage: this.search.rentalhouse.ser_acreage,
                rental_room: this.search.rentalhouse.ser_room,
                rental_direction: this.search.rentalhouse.direction,
                rental_floor: this.search.rentalhouse.floor,
                rental_renovation: this.search.rentalhouse.renovation,
                rental_type: this.search.rentalhouse.type
            }
            var that = this
            // axios.post("/maproom/scrolldata?page="+that.page,formData).then(function (res) {
            axios.post("/maproom/alldata?page="+that.page,formData).then(function (res) {
                that.loading = false
                if (!res.data.error) {
                    that.scrollData = that.scrollData.concat(res.data.scroll.data)
                }else{
                    that.nomore = res.data.message
                    that.canloading = false
                }
            }).catch(function (error) {
                that.loading = false
                that.$Message.error('系统忙，请稍后重试')
            });
        },
        // getAreaProperty(area_id){
        //     this.loading = true
        //     var formData = {
        //         city_id: this.defaultCity,
        //         area_id: area_id,
        //         sort:this.search.sort,
        //         type: this.search.type,
        //         apartname: this.search.apartname,
        //         average: this.search.newhouse.ser_average,
        //         wytype: this.search.newhouse.ser_pmc,
        //         sale_status: this.search.newhouse.ser_status,
        //         ser_price: this.search.handroom.ser_price,
        //         ser_acreage: this.search.handroom.ser_acreage,
        //         ser_room: this.search.handroom.ser_room,
        //         direction: this.search.handroom.direction,
        //         floor: this.search.handroom.floor,
        //         renovation: this.search.handroom.renovation
        //     }
        //     var that = this
        //     axios.post("/maproom/scrolldata?page="+that.page,formData).then(function (res) {
        //         that.loading = false
        //         if (!res.data.error) {
        //             that.scrollData = that.scrollData.concat(res.data.data.data)
        //         }else{
        //             that.nomore = res.data.message
        //             that.canloading = false
        //         }
        //     }).catch(function (error) {
        //         that.loading = false
        //         that.$Message.error('系统忙，请稍后重试')
        //     });
        // },
        addMarker() {
            map.clearOverlays();
            //数据
            var clustereData=this.cityData
            //     [
            //     {"name":"龙华区","code":"410100000","longitude":"110.335541","latitude":"20.036321","count":"445"},
            //     {"name":"美兰区","code":"410200000","longitude":"110.373498","latitude":"20.034646","count":"377"},
            //     {"name":"琼山区","code":"410300000","longitude":"110.360526","latitude":"20.009151","count":"370"},
            //     {"name":"秀英区","code":"410400000","longitude":"110.300436","latitude":"20.013642","count":"300"}
            // ];
            //为了提高百度地图性能，点位全用label来加载点位
            var that = this
            $.each(clustereData,function (index,data) {
                var point = new BMap.Point(data.longitude, data.latitude);
                //自定义label样式
                var tpl = '<div class="bubble bubble-1" data-longitude="' + data.longitude + '"' +
                    ' data-latitude="' + data.latitude + '" data-id="' + data.id + '">' +
                    '<p class="name" title="' + data.name + '">' + data.name + '</p>' +
                    '<p><span class="count">' + data.count + '</span>个楼盘</p>' +
                    '</div>';
                var myLabel = new BMap.Label(tpl,
                    {
                        position: point, //label 在此处添加点位位置信息
                        offset: new BMap.Size(-46, -46)
                    });
                myLabel.setStyle({
                    width: "92px",  //宽
                    height: "92px", //高度
                    border: "0",  //边
                    background: "rgba(84,144,244,.9)",    //背景颜色
                    borderRadius:"50%",
                    cursor: "pointer"
                });
                myLabel.setTitle(data.name);
                map.addOverlay(myLabel);//添加点位
                // 当鼠标悬停在label上时显示行政区划边界
                myLabel.addEventListener("mouseover", function () {
                    myLabel.setStyle({
                        background:"rgba(255, 153, 0,.9)",
                        zIndex:"4"
                    }); //修改覆盖物背景颜色
                    var regionName = myLabel.getTitle();
                    that.getBoundary(regionName);
                });
                // 当鼠标离开时在删除边界折线数据
                myLabel.addEventListener("mouseout", function () {
                    myLabel.setStyle({
                        background:"rgba(84,144,244,.9)",
                        zIndex: "1"
                    }); //修改覆盖物背景颜色
                    if (window.ply) {
                        var polyPathArray = new Array();
                        window.ply.setPath(polyPathArray);
                        map.removeOverlay(ply);//清除折线数据
                    }
                });

                myLabel.addEventListener("click", function () {
                    // 调用对应点击区域的楼盘
                    if (that.search.type == 'new') {
                        that.propertyData = that.cityData[index]['property']
                    }else if (that.search.type == 'hand') {
                        that.propertyData = that.cityData[index]['handroom']
                    }else if (that.search.type == 'rental') {
                        that.propertyData = that.cityData[index]['rentalhouse']
                    }

                    // 获取区域点位数据
                    that.scrollData = []
                    that.page = 1
                    that.areaId = that.cityData[index]['id']
                    // 当前区域
                    that.search.ser_area = that.cityData[index]['id']
                    // 清空搜索框
                    that.search.apartname = ''
                    // that.getAreaProperty(that.cityData[index]['id'])
                    that.initAllProperty(that.cityData[index]['id'])
                    map.zoomIn();
                    that.getAllLabel();//获取所有点位数据
                });

            })
        },
        getBoundary(regionName) {
            var bdary = new BMap.Boundary();
            var that = this
            bdary.get(regionName, function (rs) {
                var count = rs.boundaries.length; //行政区域的点有多少个
                if (count === 0) {
                    alert('未能获取当前输入行政区域');
                    return;
                }
                for (var i = 0; i < count; i++) {
                    if (!window.ply) {
                        window.ply = new BMap.Polygon(rs.boundaries[i], {
                            strokeWeight: 2,
                            strokeColor: "rgb(66, 133, 244)",
                            fillColor: "rgba(53, 126, 244,0.1)"
                        }); //建立多边形覆盖物
                        map.addOverlay(ply);  //添加覆盖物
                    } else {
                        window.ply.setPath(rs.boundaries[i]);
                        map.addOverlay(ply);  //添加覆盖物
                    }
                    ply.enableMassClear();
                    that.pointArray = that.pointArray.concat(ply.getPath());
                }
            });
        },
        getAllLabel() {
            map.clearOverlays();
            //点位数据
            var labelListData=this.propertyData
            //     [
            //     {"title":"碧桂园 中央半岛","id":"1","longitude":"110.368238","latitude":"20.08937","average":"10000","thumb":"/uploads/images/2019-05-26_1558857731_5cea480386a62.jpg"},
            //     {"name":"美丽沙 旅游","code":"2","longitude":"110.326221","latitude":"20.079133","num":"999","thumb":"/uploads/images/2019-05-26_1558857731_5cea480386a62.jpg"},
            //     {"name":"恒大文化旅游城","code":"3","longitude":"110.347207","latitude":"19.965975","num":"888","thumb":"/uploads/images/2019-05-26_1558857731_5cea480386a62.jpg"}
            // ];
            var that = this
            that.labelData = []
            $.each(labelListData,function (index,data) {
                if (that.search.type == 'new') {
                    var tpls = '<div class="bun-detail animated fadeInLeft" style="" title="' + data.title + '"><span class="txt nowrap">' + data.title +'</span><span class="num">'+ data.average + data.average_unit +'</span><div class="arrow"></div></div>'
                }else if (that.search.type == 'hand'){
                    var tpls = '<div class="bun-detail animated fadeInLeft" style="" title="' + data.title + '"><span class="txt nowrap">' + data.title +'</span><span class="num">'+ data.price + '万</span></span><div class="arrow"></div></div>'
                }else if (that.search.type == 'rental'){
                    var tpls = '<div class="bun-detail animated fadeInLeft" style="" title="' + data.title + '"><span class="txt nowrap">' + data.title +'</span><span class="num">'+ data.price + '元/月</span><div class="arrow"></div></div>'
                }

                var point = new BMap.Point(data.longitude, data.latitude);
                var myLabel = new BMap.Label(tpls,
                    {
                        position: point, //label 在此处添加点位位置信息
                        offset: new BMap.Size(-12, -15)
                    });
                myLabel.setStyle({
                    border: "0",  //边
                    padding: "0",
                    background: "none"
                });
                myLabel.setTitle(data.name);
                that.labelData.push(myLabel);
//            map.addOverlay(myLabel);
                //信息窗口模板
                if (that.search.type == 'new') {
                    var tpl="<div class='infoBox' data-longitude='"+data.longitude+"' data-latitude='"+data.latitude+"' data-id='"+data.id+"'>" +
                        "<img class='img' src='"+ data.thumb +"'/>" +
                        "<div class='infoArea'><p class='name nowrap'>"+data.title+"</p><p class='num'>均价<span class='red'> "+data.average+" </span>"+data.average_unit+"</p></div>" +
                        "<i class='arrow'></i></div>";
                }else if (that.search.type == 'hand'){
                    var year = ''
                    if(Number(data.year) > 0){
                        year = data.year + '年'
                    }
                    var tpl="<div class='infoBox' data-longitude='"+data.longitude+"' data-latitude='"+data.latitude+"' data-id='"+data.id+"'>" +
                        "<img class='img' src='"+ data.thumb +"'/>" +
                        "<div class='infoArea'><p class='name nowrap'>"+data.title+"</p><p class='num'>总价<span class='red'> "+data.price+"万</span>&ensp;<span>"+year+"</span></p></div>" +
                        "<i class='arrow'></i></div>";
                }else if (that.search.type == 'rental'){
                    var year = ''
                    if(Number(data.year) > 0){
                        year = data.year + '年'
                    }
                    var tpl="<div class='infoBox' data-longitude='"+data.longitude+"' data-latitude='"+data.latitude+"' data-id='"+data.id+"'>" +
                        "<img class='img' src='"+ data.thumb +"'/>" +
                        "<div class='infoArea'><p class='name nowrap'>"+data.title+"</p><p class='num'>月租<span class='red'> "+data.price+"元/月</span>&ensp;<span>"+year+"</span></p></div>" +
                        "<i class='arrow'></i></div>";
                }
                var infoBox = new BMapLib.InfoBox(map, tpl, {
                    boxStyle: {
                        width: "220px",
                        minHeight: "50px",
                        marginBottom: "26px"
                    },
                    closeIconMargin: "0 8px 0 0",
                    closeIconUrl: "/images/close.png",
                    enableAutoPan: false,
                    align: INFOBOX_AT_TOP
                });
                //鼠标点击时打开新标签并关闭上一个标签内容
                myLabel.addEventListener("mouseover", function () {
                    if (window.lastInfoBox != null) {
                        //判断上一个窗体是否存在，若存在则执行close
                        window.lastInfoBox.close();
                    }
                    this.setStyle({
                        zIndex: "4",
                    })
                    window.lastInfoBox = infoBox;
                    infoBox.open(point);
                });
                myLabel.addEventListener("mouseout", function () {
                    this.setStyle({
                        zIndex: "1",
                    })
                });
                //鼠标点击时标签一直存在
                myLabel.addEventListener("click", function () {
                    // window.lastInfoBox=null;
                    infoBox.open(point);
                    this.setStyle({
                        zIndex: "6",
                    })
                    var idattr = 'buncode'+data.code
                    $("."+idattr).addClass('bun-fixed')
                    $("."+idattr).parents().siblings().find(".bun-detail").removeClass("bun-fixed")
                    window.open("/property/"+data.id);
                });
            });
            that.addViewLabel(that.labelData);//加载可视范围点
        },
        addViewLabel(labels) {
            map.clearOverlays();
            for(var i = 0; i < labels.length; i ++){
                var result = BMapLib.GeoUtils.isPointInRect(labels[i].point, map.getBounds());
                if(result == true) {
                    map.addOverlay(labels[i])
                } else{
                    map.removeOverlay(labels[i]);
                }
            }
        },
        handleReachBottom(){
            var that = this
            that.page += 1
            if (that.canloading){
                if(that.areaId){
                    // that.getAreaProperty(that.areaId)
                    that.initAllProperty()
                }else{
                    that.initAllProperty()
                }
            }
        },
        changeSort(){
            this.search.sort = 'default'
            this.cur = 0
            this.page = 1
            this.scrollData = []
            if(this.areaId){
                // this.getAreaProperty(this.areaId)
                this.initAllProperty()
            }else{
                this.initAllProperty()
            }
        },
        changePriceSort(){
            this.page = 1
            this.cur = 1
                this.scrollData = []
            if(!this.search.newhouse.priceStatus){
                this.search.sort = 'dowm_price'
                this.search.newhouse.priceStatus = true
            }else{
                this.search.sort = 'up_price'
                this.search.newhouse.priceStatus = false
            }
            if(this.areaId){
                // this.getAreaProperty(this.areaId)
                this.initAllProperty()
            }else{
                this.initAllProperty()
            }
        },
        changeTimeSort(){
            this.page = 1
            this.cur = 2
                this.scrollData = []
            if(!this.search.newhouse.timeStatus){
                this.search.sort = 'dowm_time'
                this.search.newhouse.timeStatus = true
            }else{
                this.search.sort = 'up_time'
                this.search.newhouse.timeStatus = false
            }
            if(this.areaId){
                // this.getAreaProperty(this.areaId)
                this.initAllProperty()
            }else{
                this.initAllProperty()
            }
        },
        initArea(){
            //获取区域信息
            var formData = {city_id:this.defaultCity}
            var that = this
            axios.post('/maproom/initArea',formData).then(function (res) {
                if (!res.data.error) {
                    // 区域
                    that.search.city = res.data.city
                    // 物业类型
                    that.search.pmcType = res.data.type
                    // 朝向
                    that.search.direct = res.data.direction
                    // 装修情况
                    that.search.renovate = res.data.renovation
                    // 特色标签
                    that.search.tags = res.data.tags
                }else{
                    that.$Message.error(res.data.message)
                }
            }).catch(function (error) {

            })
        },
        handleChangeType() {
            this.handleStatus = true
            this.areaId = 0
            this.pointArray = [];//行政区划点位集合
            this.labelData=[];//存数点位数据
            // this.initMap()
            this.initSearchData()
            this.initDataFunc()
            // 关闭搜索状态,恢复可执行 handleChangeOther
            this.$nextTick(function () {
                this.handleStatus = false
            })
        },
        handleChangeArea(){
            if (!this.search.ser_area){
                this.search.ser_area = 0
            }
            if (this.search.ser_area === this.defaultCity) {
                this.areaId = 0
            }else{
                this.areaId = this.search.ser_area
            }
            if (!this.handleStatus){
                this.search.apartname = ''
            }
            this.handleChangeOther()
            // if (this.search.type === 'new') {
            //     this.handleChangeOther()
            // }else if(this.search.type === 'hand'){
            //     this.handleChangeHandroom()
            // }
        },
        handleChangeOther(){
            // 未搜索具体小区才执行
            if (!this.handleStatus) {
                this.ininDataDefault()
                this.search.sort = 'default'
                this.initDataFunc()
                this.getAllProperty()
            }

        },
        // handleChangeHandroom(){
        //     if (!this.handleStatus) {
        //         this.ininDataDefault()
        //         this.search.sort = 'default'
        //         this.initDataFunc()
        //         this.getAllProperty()
        //     }
        // },

        handleSearch(){
            // 标记搜索状态,防止重复执行 handleChangeOther
            this.handleStatus = true
            this.areaId = 0
            this.search.ser_area = 0
            this.search.sort = 'default'
            this.ininDataDefault()
            if(this.search.type === 'new'){
                this.initNewhouseData()
            }else if(this.search.type === 'hand'){
                this.initHandroomData()
            }

            this.initDataFunc()
            this.getAllProperty()
            // window.map = this.initMap(13);
            // 关闭搜索状态,恢复可执行 handleChangeOther
            this.$nextTick(function () {
                this.handleStatus = false
            })

        },
        ininDataDefault(){
            this.cityData = []
            this.propertyData = []
            this.scrollData = []
        },
        initNewhouseData(){
            this.search.newhouse.ser_average = 0
            this.search.newhouse.ser_pmc = 0
            this.search.newhouse.ser_status = 0
            this.search.newhouse.priceStatus = false
            this.search.newhouse.timeStatus = false
        },
        initHandroomData(){
            this.search.handroom.ser_price = 0
            this.search.handroom.ser_acreage = 0
            this.search.handroom.ser_room = 0
            this.search.handroom.direction = 0
            this.search.handroom.floor = 0
            this.search.handroom.renovation = 0

            this.search.newhouse.priceStatus = false
            this.search.newhouse.timeStatus = false
        },
        initSearchData(){
            this.ininDataDefault()

            // this.search.city = {}
            this.search.apartname = ''
            this.search.ser_area = 0
            this.search.sort = 'default'

            this.initNewhouseData()
            this.initHandroomData()

        },
        initDataFunc(){
            this.initCityProperty()
            this.initAllProperty()
            // window.map = this.initMap();//初始化地图对象
            window.lastInfoBox = null; //定义最近打开的地图信息窗体
            // this.pointArray = [];//行政区划点位集合
            // this.labelData=[];//存数点位数据
            // this.addMarker();//添加聚合点
            this.initArea()
        }
    },
    mounted() {
        this.initDataFunc()
        window.map = this.initMap();
        // 滚动加载的容器高度
        this.boxHeight = document.getElementById("scroll").offsetHeight;
    }
})